package cn.itcast.controller.log;


import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class AspectLog {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    @Autowired
    private SysLogService sysLogService;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {

        SysLog log = new SysLog();
        User user = (User) session.getAttribute("loginUser");

        log.setCompanyId(user.getCompanyId());
        log.setTime(new Date());
        log.setIp(request.getRemoteAddr());//获取当前登录人的ip

        if (user!=null){
            log.setId(UUID.randomUUID().toString());
            log.setUserName(user.getUserName());
            log.setCompanyName(user.getCompanyName());
        }
//        获取方法签名  方法签名中有方法的信息和注解的信息
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        log.setMethod(method.getName());//方法名
//        判断这个方法上是否有这个RequestMapping注解
        if(method.isAnnotationPresent(RequestMapping.class)){
            //            获取到这个注解
            RequestMapping annotation = method.getAnnotation(RequestMapping.class);
//            获取到这个注解名
            String action = annotation.name();

            log.setAction(action);
        }

        //保存日志
        sysLogService.save(log);
        //执行原方法

        return  pjp.proceed();//执行原方法
    }
}
